/**
 * 
 */
package com.xored.glance.internal.core;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;

import com.xored.glance.core.ISourceListener;
import com.xored.glance.core.ITextProvider;
import com.xored.glance.core.ITextSource;

/**
 * @author Yuri Strot
 * 
 */
public class TextSourceManager implements ITextProvider {

	public static TextSourceManager getInstance() {
		if (instance == null)
			instance = new TextSourceManager();
		return instance;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.xored.glance.core.ITextProvider#addSourceListener(com.xored.glance
	 * .core.ISourceListener)
	 */
	public void addSourceListener(ISourceListener listener) {
		getListener().addSourceListener(listener);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.xored.glance.core.ITextProvider#getSource()
	 */
	public ITextSource getSource() {
		return getListener().getSource();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.xored.glance.core.ITextProvider#removeSourceListener(com.xored.glance
	 * .core.ISourceListener)
	 */
	public void removeSourceListener(ISourceListener listener) {
		getListener().removeSourceListener(listener);
	}

	protected ITextProvider[] getProviders() {
		IConfigurationElement[] configs = Platform.getExtensionRegistry()
				.getConfigurationElementsFor(EXT_PROVIDER);
		if (providers == null) {
			List<ITextProvider> list = new ArrayList<ITextProvider>();

			for (IConfigurationElement config : configs) {
				try {
					ITextProvider provider = (ITextProvider) config
							.createExecutableExtension(ATTR_CLASS);
					list.add(provider);
				} catch (Exception e) {
					GlancePlugin.log(e);
				}
			}
			providers = list.toArray(new ITextProvider[list.size()]);
		}
		return providers;
	}

	protected CompositeSourceListener getListener() {
		if (listener == null)
			listener = new CompositeSourceListener(getProviders());
		return listener;
	}

	private final static String ATTR_CLASS = "class";
	private final static String EXT_PROVIDER = GlancePlugin.PLUGIN_ID
			+ ".textProvider";
	private static TextSourceManager instance;

	protected ITextProvider[] providers;
	protected CompositeSourceListener listener;

	private TextSourceManager() {
	}

}
